<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->

<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <el-row>
        <el-col :span="8"
                style='margin-top:15px;'>
          <el-tree class="filter-tree"
                   node-key="id"
                   highlight-current
                   :data="treeData"
                   :default-expanded-keys="aExpandedKeys"
                   :filter-node-method="filterNode"
                   :props="defaultProps"
                   @node-click="getNodeData"
                   @node-expand="nodeExpand"
                   @node-collapse="nodeCollapse">
          </el-tree>
        </el-col>
        <el-col :span="16" style='margin-top:15px;'>
              <div class="filter-container">
              <el-button-group v-if="showElement">
                <el-button type="primary"
                          v-if="permission.sys_base_menu_update"
                          icon="plus"
                          @click="handlerAdd">添加</el-button>
                <el-button type="primary"
                          v-if="permission.sys_base_menu_update"
                          icon="edit"
                          @click="handlerEdit">编辑</el-button>
                <el-button type="primary"
                          v-if="permission.sys_base_menu_delete"
                          icon="delete"
                          @click="handleDelete">删除</el-button>
              </el-button-group>
            </div>
            <avue-form :option="option"
              @submit="submitForm"
              v-if="showElement"
               v-model="form">
            </avue-form>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
import tableOption from '@/views/system/menu/menuOption';
import { readSystemMenuByTree,addSystemMenu,editSystemMenu,delSystemMenu } from '@/views/system/menu/menuApi'
import { mapGetters } from 'vuex'

export default {
  name: 'menu',
  data () {
    return {
      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      formStatus: '',
      showElement: false,
      listQuery: {
        name: undefined
      },
      treeData: [],
      oExpandedKey: {
        // key (from tree id) : expandedOrNot boolean
      },
      oTreeNodeChildren: {
        // id1 : [children] (from tree node id1)
        // id2 : [children] (from tree node id2)
      },
      aExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      option:tableOption,
      form: {
        permission: undefined,
        menuName: undefined,
        id: undefined,
        parentId: undefined,
        icon: undefined,
        sortNo: undefined,
        component: undefined,
        menuType: undefined,
        meta: undefined,
        btnDic: undefined,
        path: undefined
      },
      currentId: -1,
    }
  },
  created () {
    this.getList()
  },
  computed: {
    ...mapGetters([
      'elements',
      'permission'
    ])
  },
  methods: {
    getList () {
      readSystemMenuByTree(this.listQuery).then(response => {
        const data = response.data;
        this.treeData = data.data;
      })
    },

    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    nodeExpand (data) {
      let aChildren = data.children
      if (aChildren.length > 0) {
        this.oExpandedKey[data.id] = true
        this.oTreeNodeChildren[data.id] = aChildren
      }
      this.setExpandedKeys()
    },
    nodeCollapse (data) {
      this.oExpandedKey[data.id] = false
      // 如果有子节点
      this.treeRecursion(this.oTreeNodeChildren[data.id], (oNode) => {
        this.oExpandedKey[oNode.id] = false
      });
      this.setExpandedKeys()
    },
    setExpandedKeys () {
      let oTemp = this.oExpandedKey
      this.aExpandedKeys = []
      for (let sKey in oTemp) {
        if (oTemp[sKey]) {
          this.aExpandedKeys.push(parseInt(sKey));
        }
      }
    },
    treeRecursion (aChildren, fnCallback) {
      if (aChildren) {
        for (let i = 0; i < aChildren.length; ++i) {
          let oNode = aChildren[i]
          fnCallback && fnCallback(oNode)
          this.treeRecursion(oNode.children, fnCallback)
        }
      }
    },
    getNodeData (data) {
      if (!this.formEdit) {
        this.formStatus = 'update'
      }
      let menuFormData = {
        permission: data.permission,
        menuName: data.menuName,
        id: data.id,
        parentId: data.parentId,
        icon: data.icon,
        sortNo: data.sortNo,
        component: data.component,
        menuType: data.menuType,
        meta: data.meta,
        btnDic: data.btnDic,
        path: data.path
      };
      this.form = menuFormData
      tableOption.disabled = true;
      this.currentId = data.id
      this.showElement = true
    },
    handlerEdit () {
      if (this.form.id) {
        this.formEdit = false
        this.formStatus = 'update'
      }
    },
    handlerAdd () {
      this.resetForm()
      this.formEdit = false
      this.formStatus = 'create'
    },
    handleDelete () {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delSystemMenu(this.currentId).then(() => {
          this.getList()
          this.resetForm()
          this.onCancel()
          this.showElement=false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    submitForm(){
      if(this.formEdit){
        this.update();
      }else{
        this.create();
      }
    },
    update () {
      editSystemMenu(this.form).then(() => {
        this.getList()
        this.showElement=false
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    create () {
      addSystemMenu(this.form).then(() => {
        this.getList()
        this.showElement=false
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    onCancel () {
      this.formEdit = true
      this.formStatus = ''
    },
    resetForm () {
      this.form = {
        permission: undefined,
        menuName: undefined,
        id: undefined,
        parentId: this.currentId,
        icon: undefined,
        sortNo: 99,
        component: undefined,
        menuType: undefined,
        meta: undefined,
        btnDic: undefined,
        path: undefined
      }
    }
  }
}
</script>

<style lang="scss">
@import "@/styles/system.scss";
</style>